package org.jeecg.modules.supplier.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.bid.entity.Bid;
import org.jeecg.modules.bid.service.IBidService;
import org.jeecg.modules.message.service.IProcurementMessageService;
import org.jeecg.modules.supplier.Vo.SupplierMatchVo;
import org.jeecg.modules.supplier.entity.ProcUserSupplierRelation;
import org.jeecg.modules.supplier.entity.Supplier;
import org.jeecg.modules.supplier.entity.qualification;
import org.jeecg.modules.supplier.mapper.SupplierMapper;
import org.jeecg.modules.supplier.service.IProcUserSupplierRelationService;
import org.jeecg.modules.supplier.service.IQualificationService;
import org.jeecg.modules.supplier.service.ISupplierService;
import org.jeecg.modules.supplierEvaluation.entity.SupplierEvaluation;
import org.jeecg.modules.supplierEvaluation.service.ISupplierEvaluationService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SupplierServiceImpl extends ServiceImpl<SupplierMapper, Supplier> implements ISupplierService {

    @Autowired
    private SupplierMapper supplierMapper;

    @Autowired
    private IQualificationService qualificationService;

    @Autowired
    private IProcurementMessageService procurementMessageService;
    @Autowired
    private IProcUserSupplierRelationService procUserSupplierRelationService;
    @Autowired
    private IBidService bidService;

    @Autowired
    private ISupplierEvaluationService supplierEvaluationService;

    @Transactional
    public boolean saveSupplier(Supplier supplier) {
        supplier.setAuditStatus("0");
        supplier.setCreateTime(new Date());
//         procurementMessageService.sendSupplierAuditNotice(supplier.getId(), "supplier", "0",
//                "无",supplier.getCreateBy(), "superAdmin");//todo 后面获取一个审核人员列表，全部发送
        return this.save(supplier);
    }


    @Transactional//供应商-编辑
    public boolean updateSupplier(Supplier supplier) {
        supplier.setUpdateTime(new Date());
        return this.updateById(supplier);
    }


    @Transactional
    public boolean auditSupplier(String supplierid, String auditStatus, String auditOpinion, String auditor) {
        // 从数据库中根据ID获取对应的Supplier对象
        Supplier supplier = this.getById(supplierid);
        if (supplier == null) {
            log.error("供应商审核失败，供应商ID不存在: {}", supplierid);
            return false;
        }
        String supplierName = supplier.getCompanyName();
        supplier.setAuditStatus(auditStatus);//设置审核状态
        supplier.setAuditOpinion(auditOpinion);//设置审核意见
        supplier.setAuditor(auditor);//设置审核人
        supplier.setAuditTime(new Date());

        //调用public ProcUserSupplierRelation getRelationBySearchKey(String searchKey) 方法
        ProcUserSupplierRelation procUserSupplierRelation= procUserSupplierRelationService.getRelationBySearchKey(supplierid);
        String CompanyName = procUserSupplierRelation.getCompanyName();
        if(procUserSupplierRelation == null )  {
            //throw new IllegalStateException("未绑定用户");
            CompanyName = supplier.getCompanyName();
        }
        procurementMessageService.sendSupplierAuditNotice(supplierid,supplierName, auditStatus,
                auditOpinion, procUserSupplierRelation.getUserId(),CompanyName);
        return this.updateById(supplier);
    }


    public IPage<Supplier> querySupplierPage(Page<Supplier> page, Supplier supplier) {
        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(supplier.getCompanyName())) {
            queryWrapper.like("company_name", supplier.getCompanyName());
        }
        if (StringUtils.isNotBlank(supplier.getCreditCode())) {
            queryWrapper.like("credit_code", supplier.getCreditCode());
        }
        if (StringUtils.isNotBlank(supplier.getAuditStatus())) {
            queryWrapper.eq("audit_status", supplier.getAuditStatus());
        }
        if (StringUtils.isNotBlank(supplier.getEngineeringCategories())) {
            queryWrapper.like("engineering_categories", supplier.getEngineeringCategories());
        }

        queryWrapper.orderByDesc("create_time");
        return this.page(page, queryWrapper);
    }

    //供应商-Excel导入
    public Result<?> importSupplier(MultipartFile file) {
        //TODO
        try {
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            List<Supplier> list = ExcelImportUtil.importExcel(file.getInputStream(), Supplier.class, params);
            if(list != null && list.size() > 0){
                // 设置导入供应商的审核状态为"待审核"
                for (Supplier supplier : list) {
                    supplier.setAuditStatus("0"); // 0-待审核
                    supplier.setCreateTime(new Date());
                }
                this.saveBatch(list);
                return Result.OK("导入成功，共" + list.size() + "条数据");
            }else{
                return Result.error("导入数据为空");
            }
        } catch (Exception e) {
            log.error("Excel导入失败", e);
            return Result.error("导入失败：" + e.getMessage());
        }
    }

    //供应商-根据类目获取可抽签供应商
    public List<Supplier> getSuppliersForLottery(String category) {
        return supplierMapper.selectSuppliersForLottery(category);
    }


    //查看社会信用代码是否重复
    public boolean checkCreditCodeExists(String creditCode, String id) {
        String checkId = oConvertUtils.getString(id);
        return supplierMapper.checkCreditCodeExists(creditCode, checkId) > 0;
    }

    @Override
    public List<qualification> getQualificationList(String supplierId) {
        return supplierMapper.getQualificationList(supplierId);
    }

    @Override
    public Supplier getByCreditCode(String creditCode) {
        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("credit_code", creditCode);
        return this.getOne(queryWrapper);
    }

    @Override
    public void saveSupplierQualifications(List<qualification> qualifications, String supplierId) {
        if (qualifications == null || qualifications.isEmpty()) {
            return;
        }

        // 拼接资质名称
        StringBuilder qualificationName = new StringBuilder();
        for (int i = 0; i < qualifications.size(); i++) {
            qualification qualification = qualifications.get(i);
            qualification.setSupplierId(supplierId);

            // 拼接资质名称
            qualificationName.append(qualification.getQualificationName());

            // 如果不是最后一个元素，则添加逗号分隔符
            if (i < qualifications.size() - 1) {
                qualificationName.append(", ");
            }
        }

        // 保存资质名称到供应商表
        savequalificationName(qualificationName.toString(), supplierId);
    }


    public void savequalificationName(String string ,String Id) {
        Supplier supplier =this.getById(Id);
        supplier.setQualificationName(string);
        this.updateSupplier(supplier);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> batchImportMultiTableData(MultipartFile file, String importType) {
        try {
            // 1. 导入供应商表数据（第一个sheet）
            ImportParams supplierParams = new ImportParams();
            supplierParams.setTitleRows(1);
            supplierParams.setHeadRows(1);
            supplierParams.setNeedSave(false); // 禁用自动保存，完全由代码控制保存逻辑
            supplierParams.setStartSheetIndex(0); // 第一个sheet
            supplierParams.setSheetNum(1); // 只读取第一个sheet

            List<Supplier> supplierList = ExcelImportUtil.importExcel(file.getInputStream(), Supplier.class, supplierParams);
            log.info("读取到供应商数据行数: {}", supplierList.size());

            // 验证统一社会信用代码是否重复
            for (Supplier supplier : supplierList) {
                if (this.checkCreditCodeExists(supplier.getCreditCode(), null)) {
                    return Result.error("统一社会信用代码 " + supplier.getCreditCode() + " 已存在，请检查Excel文件");
                }
                // 审核状态设置默认值
                if (supplier.getAuditStatus() == null) {
                    supplier.setAuditStatus("0"); // 0-待审核
                }
                if (supplier.getCreateTime() == null) {
                    supplier.setCreateTime(new Date());
                }
            }

            // 保存供应商数据
            boolean supplierSaved = this.saveBatch(supplierList);
            log.info("供应商数据保存结果: {}, 行数: {}", supplierSaved, supplierList.size());

            // 2. 导入资质表数据（第二个sheet）
            // 重要：重新获取文件输入流，避免reset可能导致的问题
            InputStream fileInputStream = file.getInputStream();
            ImportParams qualificationParams = new ImportParams();
            qualificationParams.setTitleRows(1);
            qualificationParams.setHeadRows(1);
            qualificationParams.setNeedSave(false); // 完全禁用自动保存
            qualificationParams.setStartSheetIndex(1); // 第二个sheet
            qualificationParams.setSheetNum(1); // 只读取第二个sheet

            List<qualification> qualificationList = ExcelImportUtil.importExcel(fileInputStream, qualification.class, qualificationParams);
            log.info("读取到资质数据行数: {}", qualificationList.size());

            // 处理并保存资质数据
            if (qualificationList != null && !qualificationList.isEmpty()) {
                Date now = new Date();
                int validCount = 0;
                int invalidCount = 0;
                List<qualification> validQualifications = new ArrayList<>();

                // 创建供应商信用代码到ID的映射，用于快速查找
                Map<String, String> creditCodeToSupplierIdMap = new HashMap<>();
                for (Supplier supplier : supplierList) {
                    if (StringUtils.isNotBlank(supplier.getCreditCode())) {
                        creditCodeToSupplierIdMap.put(supplier.getCreditCode(), supplier.getId());
                    }
                }

                for (qualification qual : qualificationList) {
                    // 设置创建时间和更新时间
                    qual.setCreateTime(now);
                    qual.setUpdateTime(now);

                    // 详细日志记录资质对象的所有字段
                    log.info("资质数据详情 - ID: {}, SupplierId: {}, CreditCode: {}, QualificationName: {}, QualificationLevel: {}",
                        qual.getId(), qual.getSupplierId(), qual.getCreditCode(), qual.getQualificationName(), qual.getQualificationLevel());

                    // 重要：根据统一社会信用代码关联供应商ID
                    if (StringUtils.isBlank(qual.getSupplierId()) && StringUtils.isNotBlank(qual.getCreditCode())) {
                        String supplierId = creditCodeToSupplierIdMap.get(qual.getCreditCode());
                        if (StringUtils.isNotBlank(supplierId)) {
                            qual.setSupplierId(supplierId);
                            log.info("通过信用代码自动关联供应商ID: {}", supplierId);
                        }
                    }

                    // 验证必填字段
                    boolean isQualValid = true;
                    if (StringUtils.isBlank(qual.getSupplierId())) {
                        log.warn("资质数据缺少供应商ID，行数据: {}", qual);
                        isQualValid = false;
                    }

                    if (StringUtils.isBlank(qual.getQualificationName())) {
                        log.warn("资质数据缺少资质名称(必填)，行数据: {}", qual);
                        isQualValid = false;
                    }

                    // 验证供应商ID是否有效
                    if (isQualValid) {
                        Supplier supplier = this.getById(qual.getSupplierId());
                        if (supplier != null) {
                            validCount++;
                            validQualifications.add(qual);
                            log.info("资质数据验证通过，关联供应商: {}", supplier.getCompanyName());
                        } else {
                            invalidCount++;
                            log.warn("资质数据的供应商ID不存在: {}", qual.getSupplierId());
                        }
                    } else {
                        invalidCount++;
                    }
                }

                log.info("资质数据验证结果: 有效行数={}, 无效行数={}", validCount, invalidCount);

                // 只保存验证通过的数据到资质表
                if (!validQualifications.isEmpty()) {
                    boolean qualificationSaved = qualificationService.saveBatch(validQualifications);
                    log.info("资质数据保存结果: {}, 实际保存行数: {}", qualificationSaved, validQualifications.size());
                } else {
                    log.warn("没有通过验证的资质数据，不执行保存操作");
                }
            }

            return Result.ok("文件导入成功！供应商数据行数：" + supplierList.size() + "，资质数据行数：" + (qualificationList != null ? qualificationList.size() : 0));

        } catch (IOException e) {
            log.error("文件导入失败: " + e.getMessage(), e);
            return Result.error("文件导入失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("文件导入失败: " + e.getMessage(), e);
            return Result.error("文件导入失败: " + e.getMessage());
        } finally {
            try {
                // 确保关闭文件流
                if (file != null) {
                    InputStream inputStream = file.getInputStream();
                    if (inputStream != null) {
                        inputStream.close();
                    }
                }
            } catch (IOException e) {
                log.error("关闭文件流失败", e);
            }
        }
    }

    @Override
    public List<String> getSupplierIdByName(String supplierName) {

            // 根据供应商名称模糊查询供应商列表
            QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(supplierName)) {
                queryWrapper.like("company_name", supplierName);
            }
            List<Supplier> supplierList = this.list(queryWrapper);
            // 提取供应商ID列表
            return supplierList.stream()
                    .map(Supplier::getId)
                    .collect(Collectors.toList());

    }

    @Override
    public String getCreditCodeBySupplierId(String supplierId) {
        // 根据供应商ID查询供应商信用代码
        String creditCode = supplierMapper.getcreditCodeBySupplierId(supplierId);
      if (creditCode == null){
          return null;
      }
        return creditCode;
    }


    @Override
    public List<SupplierMatchVo> getSupplierMatch(String category) {
        // 添加类目空值校验（可选参数，但为空时仍需处理）
        if (StringUtils.isEmpty(category)) {
            log.info("【供应商】获取抽签供应商: 类目为空，返回全部供应商");
        }

        List<Supplier> suppliersMatch = this.getSuppliersForLottery(category);

        // 转换为SupplierMatchVo列表
        return suppliersMatch.stream().map(supplier -> {
            SupplierMatchVo vo = new SupplierMatchVo();
            // 设置供应商基本信息
            vo.setSupplierId(supplier.getId());
            vo.setSupplier(supplier.getCompanyName()); // 供应商名称
            vo.setCategory(supplier.getEngineeringCategories()); // 类目

            // 获取并设置资质信息
            vo.setQualifications(supplier.getQualificationName());

            // 设置评分（这里假设使用供应商的评分字段，如果有的话）
            vo.setAvgScore(supplier.getAvgScore()); // 评分

            // 设置中签率（需要根据实际业务逻辑计算）
            vo.setWinningRate(supplier.getWinningRate()); // 中签率

            // 设置最近中标时间
            // 从proc_bid表查询is_winning=1的最新记录
            QueryWrapper<Bid> bidQueryWrapper = new QueryWrapper<>();
            bidQueryWrapper.eq("supplier_id", supplier.getId());
            bidQueryWrapper.eq("is_winning", 1); // 中标状态
            bidQueryWrapper.orderByDesc("winning_time");
            List<Bid> winningBids = bidService.list(bidQueryWrapper);
            if (winningBids != null && !winningBids.isEmpty()) {
                vo.setWinningTime(winningBids.get(0).getWinningTime()); // 最近中标时间
            }

            // 设置未完工项目信息
            // 从proc_supplier_evaluation表查询onTimeCompletion不为0并且purchaseId不能重复，如果重复的，按创建时间最新的算
            // 构建查询条件：指定供应商ID、onTimeCompletion不为0、按创建时间降序排序
            QueryWrapper<SupplierEvaluation> evaluationQueryWrapper = new QueryWrapper<>();
            evaluationQueryWrapper.eq("supplier_id", supplier.getId());
            evaluationQueryWrapper.ne("on_time_completion", 0);
            evaluationQueryWrapper.orderByDesc("create_time");

            // 获取所有符合条件的评价记录
            List<SupplierEvaluation> allEvaluations = supplierEvaluationService.list(evaluationQueryWrapper);

            // 使用LinkedHashMap确保保留首次插入的顺序（即时间最新的记录），并按purchaseId去重
            Map<String, SupplierEvaluation> uniqueEvaluationsMap = new java.util.LinkedHashMap<>();
            for (SupplierEvaluation eval : allEvaluations) {
                if (StringUtils.isNotBlank(eval.getPurchaseId()) && !uniqueEvaluationsMap.containsKey(eval.getPurchaseId())) {
                    uniqueEvaluationsMap.put(eval.getPurchaseId(), eval);
                }
            }

            // 转换为List
            List<SupplierEvaluation> evaluations = new java.util.ArrayList<>(uniqueEvaluationsMap.values());
            StringBuilder unfinishedProjectNames = new StringBuilder();
            int unfinishedCount = 0;

            if (evaluations != null && !evaluations.isEmpty()) {
                for (SupplierEvaluation evaluation : evaluations) {
                    // 假设onTimeCompletion字段为0表示按时完成，非0表示未按时完成
                    if (evaluation.getOnTimeCompletion() != null && evaluation.getOnTimeCompletion() != 0) {
                        unfinishedCount++;
                        if (StringUtils.isNotBlank(evaluation.getProjectName())) {
                            if (unfinishedProjectNames.length() > 0) {
                                unfinishedProjectNames.append("，");
                            }
                            unfinishedProjectNames.append(evaluation.getProjectName());
                        }
                    }
                }
            }

            vo.setUnfinishedProject(unfinishedCount); // 未完工项目数量
            vo.setUnfinishedProjectName(unfinishedProjectNames.toString()); // 未完成项目名称

            return vo;
        }).collect(java.util.stream.Collectors.toList());
    }
}
